package com.gpframework.module.service.system.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.constant.BrandConstants;
import com.gpframework.common.constant.UserConstants;
import com.gpframework.common.core.domain.TreeSelect;
import com.gpframework.common.core.domain.TreeSelectVo;
import com.gpframework.common.core.domain.entity.*;
import com.gpframework.common.enums.CommonOrderAuditEnum;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.module.domain.BrandInfo;
import com.gpframework.module.module.domain.vo.BrandInfoVo;
import com.gpframework.module.module.service.IBrandInfoService;
import com.gpframework.module.pay.utils.joinpay.sdk.utitls.StringUtil;
import com.gpframework.module.service.system.IPlatformMenuService;
import com.gpframework.module.system.domain.SysRoleMenu;
import com.gpframework.module.system.domain.vo.MetaVo;
import com.gpframework.module.system.domain.vo.RouterVo;
import com.gpframework.module.system.mapper.*;
import com.gpframework.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @Author gpframework
 */
@Service
public class PlatformMenuServiceImpl implements IPlatformMenuService {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private PlatformMenuMapper platformMenuMapper;

    @Autowired
    private PlatformRoleMapper platformRoleMapper;

    @Autowired
    private PlatformRoleMenuMapper platformRoleMenuMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private IBrandInfoService brandInfoService;

    /**
     * 生成雪花id
     */
    private Snowflake snowflake = IdUtil.getSnowflake(1, 1);

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */
    @Override
    public List<PlatformMenu> selectMenuList(Long userId) {
        return selectMenuList(new PlatformMenu(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<PlatformMenu> selectMenuList(PlatformMenu menu, Long userId) {
        List<PlatformMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId) || YesNoEnum.YES.getKey().equals(menu.getIsAuthorization())) {
            menuList = platformMenuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = platformMenuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = platformMenuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */
    @Override
    public List<PlatformMenu> selectMenuTreeByUserId(Long userId) {
        List<PlatformMenu> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = platformMenuMapper.selectMenuTreeAll();
        } else {
            menus = platformMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Integer> selectMenuListByRoleId(Long roleId) {
        PlatformRole role = platformRoleMapper.selectRoleById(roleId);
        return platformMenuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    /**
     * 根据品牌ID查询菜单树信息
     *
     * @param brandId 角色ID
     * @return
     */
    @Override
    public List<String> selectBrandMenuListByRoleId(Long brandId) {
        return sysMenuMapper.selectMenuIdList(brandId);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<PlatformMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (PlatformMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
            List<PlatformMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMeunFrame(menu)) {
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<PlatformMenu> buildMenuTree(List<PlatformMenu> menus) {
        List<PlatformMenu> returnList = new ArrayList<PlatformMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (PlatformMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (Iterator<PlatformMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            PlatformMenu menu = (PlatformMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<PlatformMenu> menus) {
        List<PlatformMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectVo> buildMenuTreeSelectVo(List<PlatformMenu> menus) {
        List<PlatformMenu> menuTrees = buildMenuTree(menus);
        List<PlatformMenuVo> sysMenuVoList = Convert.convert(new TypeReference<List<PlatformMenuVo>>() {
        }, menuTrees);
        return sysMenuVoList.stream().map(TreeSelectVo::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public PlatformMenu selectMenuById(Long menuId) {
        return platformMenuMapper.selectMenuById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int result = platformMenuMapper.hasChildByMenuId(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = platformRoleMenuMapper.checkMenuExistRole(menuId);
        return result > 0 ? true : false;
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(PlatformMenu menu) {
        menu.setCode(snowflake.nextIdStr());
        return platformMenuMapper.insertMenu(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(PlatformMenu menu) {
        return platformMenuMapper.updateMenu(menu);
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return platformMenuMapper.deleteMenuById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(PlatformMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        PlatformMenu info = platformMenuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(PlatformMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMeunFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(PlatformMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeunFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(PlatformMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMeunFrame(menu)) {
            component = menu.getComponent();
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMeunFrame(PlatformMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<PlatformMenu> getChildPerms(List<PlatformMenu> list, int parentId) {
        List<PlatformMenu> returnList = new ArrayList<>();
        for (Iterator<PlatformMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            PlatformMenu t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<PlatformMenu> list, PlatformMenu t) {
        // 得到子节点列表
        List<PlatformMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (PlatformMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<PlatformMenu> getChildList(List<PlatformMenu> list, PlatformMenu t) {
        List<PlatformMenu> tlist = new ArrayList<PlatformMenu>();
        Iterator<PlatformMenu> it = list.iterator();
        while (it.hasNext()) {
            PlatformMenu n = (PlatformMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<PlatformMenu> list, PlatformMenu t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }


    /**
     * 授权品牌目录
     *
     * @param sysMenuVo
     * @return
     */
    @Override
    @Transactional
    public boolean authorizationBrandMenu(SysMenuVo sysMenuVo) {
        //授权的列表
        List<PlatformMenu> platformMenuList = platformMenuMapper.findCodeList(sysMenuVo.getCodeList());
        SysMenu sysMenu = new SysMenu();
        sysMenu.setBrandId(Long.parseLong(sysMenuVo.getBrandId()));
        //现品牌拥有列表
        List<SysMenu> haveMenuList = sysMenuMapper.selectMenuList(sysMenu);
        //需授权的list
        List<SysMenu> authorizationMenuList = Convert.convert(new TypeReference<List<SysMenu>>() {
        }, platformMenuList);
        //需删除的目录
        List<SysMenu> removeMenuList = haveMenuList.stream()
                .filter(m1 -> !authorizationMenuList.stream().map(SysMenu::getCode).collect(Collectors.toList()).contains(m1.getCode())).collect(Collectors.toList());
        //删除菜单
        removeMenuList.forEach(item -> sysMenuMapper.deleteMenuById(item.getMenuId()));
        //移除相同目录的授权
/*        List<SysMenu> collect = authorizationMenuList.stream()
                .filter(m1 -> !haveMenuList.stream().map(SysMenu::getCode).collect(Collectors.toList()).contains(m1.getCode())).collect(Collectors.toList());*/
        //需授权的目录树
/*        List<SysMenu> newMenu = collect.stream().filter(m -> m.getParentId() == 0).peek(
                (m) -> m.setChildren(getChildrens(m, collect))
        ).collect(Collectors.toList());*/
        List<SysMenu> newMenu = authorizationMenuList.stream().filter(m -> m.getParentId() == 0).peek(
                (m) -> m.setChildren(getChildrens(m, authorizationMenuList))
        ).collect(Collectors.toList());
        //新增目录权限
        addBrandMenu(newMenu, Long.parseLong(sysMenuVo.getBrandId()), null);
        return true;
    }


    /**
     * 授权所有品牌目录
     *
     * @param sysMenuVo
     * @return
     */
    @Override
    @Transactional
    public boolean authorizationAllBrandMenu(SysMenuVo sysMenuVo) {
        //授权的列表
        List<PlatformMenu> platformMenuList = platformMenuMapper.findCodeList(sysMenuVo.getCodeList());
        //需授权的list
        List<SysMenu> authorizationMenuList = Convert.convert(new TypeReference<List<SysMenu>>() {
        }, platformMenuList);
        // 获取所有品牌
        List<BrandInfoVo> brandList = brandInfoService.listVo(new QueryWrapper<BrandInfo>().eq("gp.del_status", YesNoEnum.NO).eq("gp.audit_status", CommonOrderAuditEnum.AUDIT_SUCCEED.getKey()));

        SysMenu sysMenu = new SysMenu();
        List<SysMenu> newMenu;
        List<SysMenu> removeMenuList;
        for (BrandInfoVo brandInfoVo : brandList) {
            Long brandId = brandInfoVo.getBrandId();
//            Long brandId = 1622767219031310337L;
            sysMenu.setBrandId(brandId);
            //现品牌拥有列表
            List<SysMenu> haveMenuList = sysMenuMapper.selectMenuList(sysMenu);
            //需删除的目录
            List<SysMenu> newMenuList = authorizationMenuList.stream()
                    .filter(m1 -> !haveMenuList.stream().map(SysMenu::getCode).collect(Collectors.toList()).contains(m1.getCode())).collect(Collectors.toList());
            newMenu = newMenuList.stream().filter(m -> m.getParentId() == 0).peek(
                    (m) -> m.setChildren(getChildrens(m, newMenuList))
            ).collect(Collectors.toList());
            //新增目录权限
            addBrandMenu(newMenu, brandId, null);
        }
        return true;
    }

    /**
     * 授权品牌目录
     *
     * @param newMenu
     * @param brandId
     * @return
     */
    private int addBrandMenu(List<SysMenu> newMenu, Long brandId, Long pid) {
        int i = 0;
        for (SysMenu menu : newMenu) {
            menu.setMenuId(snowflake.nextId());
            menu.setBrandId(brandId);
            menu.setVisible("0");
            if (menu.getParentId() != 0) {
                menu.setMenuId(snowflake.nextId());
                menu.setParentId(pid);
            }
            List<SysMenu> sysMenuList = sysMenuMapper.selectMenuList(menu);
            if (StringUtil.isEmpty(sysMenuList) || sysMenuList.size() <= 0) {
                sysMenuMapper.insertMenu(menu);
                saveRoleMenu(menu, BrandConstants.WE_CHAT_BRAND_ADMIN);
            } else {
                SysMenu sysMenu = sysMenuList.get(0);
                menu.setMenuId(sysMenu.getMenuId());
                sysMenu.setMenuName(menu.getMenuName());
                sysMenu.setPath(menu.getPath());
                sysMenu.setComponent(menu.getComponent());
                sysMenu.setPerms(menu.getPerms());
                sysMenu.setOrderNum(menu.getOrderNum());
                sysMenuMapper.updateMenu(sysMenu);
            }
            if (!org.springframework.util.StringUtils.isEmpty(menu.getChildren()) && menu.getChildren().size() > 0) {
                long menuId = menu.getMenuId();
                i += addBrandMenu(menu.getChildren(), brandId, menuId);
            }
        }
        return i;
    }

    /**
     * 获取目录树
     *
     * @param menu
     * @param all
     * @return
     */
    private List<SysMenu> getChildrens(SysMenu menu, List<SysMenu> all) {
        List<SysMenu> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), menu.getMenuId());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }

    /**
     * 设置品牌角色权限
     *
     * @param menu
     * @param roleKey
     * @return
     */
    private boolean saveRoleMenu(SysMenu menu, String roleKey) {
        if (StringUtil.isEmpty(menu) || StringUtil.isEmpty(roleKey)) {
            return false;
        }
        SysRole brandRole = sysRoleMapper.getBrandRole(menu.getBrandId(), BrandConstants.WE_CHAT_BRAND_ADMIN);
        if (StringUtil.isEmpty(brandRole)) {
            logger.info("-----------找不到角色信息" + brandRole + "-----------");
            return false;
        }
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        sysRoleMenu.setBrandId(menu.getBrandId());
        sysRoleMenu.setBrandMenuId(menu.getMenuId());
        sysRoleMenu.setBrandRoleId(brandRole.getBrandRoleId());
        sysRoleMenuMapper.saveRoleMenu(sysRoleMenu);
        return true;
    }
}
